package.cpath = "luaclib/?.so"

if _VERSION ~= "Lua 5.4" then
	error "Use lua 5.4"
end

local usrName

print("Please enter your name to chat: ")
usrName = io.read()
print("The name your enter is: ", usrName)


local socket = require "client.socket"
local fd = assert(socket.connect("127.0.0.1", 8888))



--socket.send(fd, "Hello world")
while true do
    -- 接收服务器返回消息
    local str   = socket.recv(fd)
    if str~=nil and str~="" then
        local message = {}
        message[1], message[2] = str:match("(%w+)(.+)")
        print(message[1].." says: "..message[2])
        
        -- socket.close(fd)
        -- break;
    end
 
    -- 读取用户输入消息
    if hasName == false then
        -- print("Please enter your name to chat: ")
        -- usrName = io.read("*l")
        -- print("The name your enter is: ", usrName)
        -- hasName = true
    else
        local readstr = socket.readstdin()
        if readstr then
            if readstr == "quit" then
                socket.close(fd)
                break;
            else
                -- 把用户输入消息发送给服务器
                readstr = usrName.." "..readstr
                socket.send(fd, readstr)
            end
        else
            socket.usleep(100)
        end
    end
end